package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constan.ProductConstant;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.AttrService;
import com.atguigu.gulimall.product.vo.AttrGroupRelationVo;
import com.atguigu.gulimall.product.vo.AttrReVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    AttrAttrgroupRelationDao relationDao;
    @Autowired
    AttrGroupDao attrGroupDao;
    @Autowired
    CategoryDao categoryDao;
    @Autowired
    CategoryServiceImpl categoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );
        return new PageUtils(page);
    }

    /**
     * 保存操作
     * @param attr
     */
    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        //把页面传入的数据copy到pojo中
        BeanUtils.copyProperties(attr,attrEntity);
        //把数据保存到数据库中
        this.save(attrEntity);
        //关联数据
        if (attr.getAttrType()== ProductConstant.attrEnum.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationDao.insert(relationEntity);
        }
    }

    /**
     * 查询规格参数列表
     * @param params
     * @param catelogId
     * @param type
     * @return
     */
    @Override
    public PageUtils queryBasePageAttr(Map<String, Object> params, Long catelogId, String type) {

        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(type)?ProductConstant.attrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.attrEnum.ATTR_TYPE_SALE.getCode());
        //如果id不为0
        if (catelogId!=0){
            //根据分类id查询
            wrapper.eq("catelog_id",catelogId);
        }

        String key = (String) params.get("key");
        //如果key不为0
        if (!StringUtils.isEmpty(key)){
            //封装查询条件
            wrapper.and((wpp)->{
                wpp.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();

        //遍历这个集合
        List<AttrReVo> attrReVos = records.stream().map((attrEntity) -> {

            AttrReVo attrReVo = new AttrReVo();
            BeanUtils.copyProperties(attrEntity, attrReVo);
            //如果type等于base的话则查询分组名字
            if ("base".equalsIgnoreCase(type)){
                //根据id查询attr_id查询分组AttrAttrgroupRelationEntity
                AttrAttrgroupRelationEntity attr_id = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (attr_id != null && attr_id.getAttrGroupId() != null) {
                    //在根据AttrAttrgroupRelationEntity里的分组id查询分组表
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrEntity.getCatelogId());
                    //把获取到的名字放入回显数据里面
                    attrReVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            //查询分类名字
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                //放入回显数据中
                attrReVo.setCatelogName(categoryEntity.getName());
            }
            return attrReVo;
        }).collect(Collectors.toList());
        pageUtils.setList(attrReVos);
        return  pageUtils;
    }

    /**
     * 根据id查询信息数据后 回显给前台页面
     * @param attrId
     * @return
     */
    @Override
    @Transactional
    public AttrReVo getAttrInfo(Long attrId) {
        AttrReVo attrReVo = new AttrReVo();
        //根据id查询商品基本属性
        AttrEntity byId = this.getById(attrId);
        BeanUtils.copyProperties(byId,attrReVo);
        //根据attrid查询分组名称
        AttrAttrgroupRelationEntity attr_id = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        if (attr_id!=null){
            attrReVo.setAttrGroupId(attr_id.getAttrGroupId());
            //通过分组id获取获取分组名称
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attr_id.getAttrGroupId());
            if (attrGroupEntity!=null){
                attrReVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }

        //获取分类完整路径
        Long[] longs = categoryService.queryCategoryIdPath(byId.getCatelogId());
        attrReVo.setCatelogPath(longs);
        CategoryEntity categoryEntity = categoryDao.selectById(byId.getCatelogId());
        if (categoryEntity!=null){
            attrReVo.setCatelogName(categoryEntity.getName());
        }
        return attrReVo;
    }

    /**
     * 修改
     * @param attr
     */
    @Override
    @Transactional
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);
        //如果是基本属性 则实现分组
        if (attr.getAttrType()==ProductConstant.attrEnum.ATTR_TYPE_BASE.getCode()){
            //修改关联分组信息
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            Integer count = relationDao.selectCount(new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if(count>0){
                //修改
                relationDao.update(attrAttrgroupRelationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));
            }else {
                //更新
                relationDao.insert(attrAttrgroupRelationEntity);
            }
        }
    }

    /**
     * 获取分组属性的所有信息
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        //通过分组id查询AttrAttrgroupRelationEntity表中所有和分组id所关联的信息
        List<AttrAttrgroupRelationEntity> group_id = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        //遍历这个集合

        List<AttrEntity> collect = group_id.stream().map((attr) -> {
            Long attrId = attr.getAttrId();
            if (attrId==null){
                return null;
            }
            AttrEntity byId = this.getById(attrId);
            return byId;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 删除分组关联关系
     * @param vos
     */
    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        List<AttrAttrgroupRelationEntity> collect = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, attrAttrgroupRelationEntity);
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());
        //删除分组的关联关系
        relationDao.deleteList(collect);
    }

    /**
     * 获取属性分组里面还没有关联的本分类里面的其他基本属性，方便添加新的关联
     * @param parms
     * @param categoryId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> parms, Long categoryId) {
        //1.当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(categoryId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //2.当前分组只能关联别的分组没有引用的属性
        //2.1）当前分类下的其他分组
        List<AttrGroupEntity> entities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> list = entities.stream().map(item -> {
            Long attrGroupId = item.getAttrGroupId();
            return attrGroupId;
        }).collect(Collectors.toList());
        //2.2）这些分组关联的属性
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", list));
        List<Long> collect = relationEntities.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //2.3）从当前分类的所有属性中移除这些属性
        //List<AttrEntity> attr_id = this.baseMapper.selectList(new QueryWrapper<AttrEntity>().eq("catelog_id",catelogId).ne("attr_id", collect));
        //模糊查询
        String key = (String) parms.get("key");
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", ProductConstant.attrEnum.ATTR_TYPE_BASE.getCode());
        if (collect!=null&&collect.size()>0){
            wrapper.notIn("attr_id", collect);
        }
        if (!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                wrapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(parms), wrapper);

        return new PageUtils(page);
    }

    /**
     * 查询状态等于1的attrid
     * @param collect
     * @return
     */
    @Override
    public List<Long> selectSeach(List<Long> collect) {
        return  this.baseMapper.selectType(collect);

    }


}